package com;
//手动提交事务_转账
import java.sql.*;

public class Demo5 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        Savepoint abc =null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得链接
            String userName="root";
            String passWord="123456";
            String url="jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";
            connection = DriverManager.getConnection(url,userName,passWord);
            connection.setAutoCommit(false);//设置成手动提交
            //3.定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            int result = statement.executeUpdate("update money set yue=yue - 100 where userid=1");
            //abc = connection.setSavepoint("abc");//这一行是添加了一个保存点，可以选择只rollback到保存点
            int result2= statement.executeUpdate("update money set yue = yue + 100 where userid = 2");
            //代码方式提交事务
            //System.out.println(5/0);
            connection.commit();
            if (result2>0){
                System.out.println("执行成功");
            }else {
                System.out.println("执行失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            }catch (SQLException throwables){
                throwables.printStackTrace();
            }
        } finally {
            //关闭资源
            try {
                if(statement != null){
                    statement.close();
                }
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
